package ar.edu.caece.pl.main;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class CleanAndCompileAll extends Compiler{
	
	static boolean debugMode = true;
	static int runOK = 0;
	static int runFail = 0;
	static List<String> testFails;
	
	public static void main(String[] args) {
		runOK = 0;
		runFail = 0;
		testFails = new ArrayList<String>();
		
		File file = new File("tests/");
        File[] files = file.listFiles();
        
        File file2 = new File("tests/functional/");
        File[] files2 = file2.listFiles();
        
        File file3 = new File("tests/functional/withErrors/");
        File[] files3 = file3.listFiles();
        
        
        cleanASM(files);
        cleanASM(files2);
        cleanASM(files3);
		
		proccessFiles(files);
		proccessFiles(files2);
		proccessFiles(files3);
		
		printFinalResults();
		
	}

	private static void printFinalResults() {
		String line = "====================";
		System.out.println(line);
		int tests = runOK+runFail;
		System.out.println("Test Corridos: " + tests);
		if (runFail > 0){
			System.err.println("Test Fallidos: " + runFail + " " + testFails.toString());
			System.out.println("Test OKs: " + runOK);
		}else{
			System.out.println("Todos los Tests corrieron OK!");
		}
		System.out.println(line);
	}

	private static void cleanASM(File[] files) {
        if (files != null) {
        	for (int i = 0; i < files.length; i++) {
        		try{
        			if (files[i].getName().endsWith(".asm")){
        				if(files[i].delete()){
        					System.out.println(files[i].getName() + " is deleted!");
        				}else{
        					System.out.println("Delete operation is failed.");
        				}
            		}
        		}catch (Exception e){
        			System.err.println("Error al compilar: " + files[i] + ". "+ e.toString());
        		}
            }
        }
	}

	private static void proccessFiles(File[] files) {
		
		if (files != null) {
        	for (int i = 0; i < files.length; i++) {
        		try{
        			if (files[i].getName().endsWith("Test")){
                        Compiler compiler = new Compiler();
        				compiler.setFile(files[i]);
        				if (compiler.compile(false)){
        					runOK++;
        				}else{
        					runFail++;
        					testFails.add(files[i].getName());
        				}
            		}
        		}catch (Exception e){
        			System.err.println("Error al compilar: " + files[i] + ". "+ e.toString());
        		}
        		
            }
        }
	}
}
